// ------------------------------------
// Reducer
// ------------------------------------
import { createReducer, statusToError, getStatusError } from 'http-services'
import * as types from './constant'

const initState = {
  getInfoPending: false,
  getInfoError: -1,
  getInfoMessage: null,
  infoData: {},
  setInfoPending: false,
  setInfoError: -1,
  setInfoMessage: null
}

const ACTION_HANDLERS = {
  [types.PROTO_FETCH_GETINFO_BEGIN]: (state, action) => {
    return {
      ...state,
      getInfoPending: true,
      getInfoError: -1,
      getInfoMessage: null
    }
  },
  [types.PROTO_FETCH_GETINFO_SUCCESS]: (state, action) => {
    const { payload } = action
    const { data, Status } = payload
    let newState = null
    if (data && Status.code === 0) {
      newState = {
        infoData: {
          ...state.infoData,
          ...data
        }
      }
    }
    return {
      ...state,
      ...statusToError(payload, 'getInfoError', 'getInfoMessage'),
      getInfoPending: false,
      ...newState
    }
  },
  [types.PROTO_FETCH_GETINFO_FAILURE]: (state, action) => {
    const { error } = action
    const status = getStatusError(error)
    return {
      ...state,
      ...statusToError({ status }, 'getInfoError', 'getInfoMessage'),
      getInfoPending: false,
    }
  },
  [types.PROTO_FETCH_SETINFO_BEGIN]: (state, action) => {
    return {
      ...state,
      setInfoPending: true,
      setInfoError: -1,
      setInfoMessage: null
    }
  },
  [types.PROTO_FETCH_SETINFO_SUCCESS]: (state, action) => {
    const { payload } = action
    const { data, Status } = payload
    let newState = null
    if (data && Status.code === 0) {
      /*newState = {
        infoData: {
          ...state.infoData,
          ...data
        }
      }*/
    }
    return {
      ...state,
      ...statusToError(payload, 'setInfoError', 'setInfoMessage'),
      setInfoPending: false,
      ...newState
    }
  },
  [types.PROTO_FETCH_SETINFO_FAILURE]: (state, action) => {
    const { error } = action
    const status = getStatusError(error)
    return {
      ...state,
      ...statusToError({ status }, 'setInfoError', 'setInfoMessage'),
      setInfoPending: false,
    }
  },
}

export default (state = initState, action) => createReducer(state, action, ACTION_HANDLERS)